package com.sgy.zookeeper_api;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CreateNote implements Watcher {

    // 允许等待一个线程
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /*
        建立会话
     */
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        /*
        * connectString：连接地址（ip:port）
        * sessionTimeout：会话超时时间
        * watcher：监听器
        * */
        zooKeeper = new ZooKeeper("192.168.201.129:2181", 30000, new CreateNote());
        System.out.println(zooKeeper.getState());

        Thread.sleep(Integer.MAX_VALUE);


    }

    /**
     * 回调方法：处理来自服务器端的watcher通知
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println(watchedEvent.getState());
        // SyncConnected
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 创建节点
            try {
                createNoteSync();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (KeeperException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 创建节点
     */
    private static void createNoteSync() throws InterruptedException, KeeperException {
        /**
         * path ：节点创建的路径
         * data[] ：节点创建要保存的数据，是个byte类型的
         * acl ：节点创建的权限信息(4种类型)
         *              ANYONE_ID_UNSAFE : 表示任何⼈
         *              AUTH_IDS ：此ID仅可⽤于设置ACL。它将被客户机验证的ID替换。
         *              OPEN_ACL_UNSAFE ：这是⼀个完全开放的ACL(常⽤)-->world:anyone
         *              CREATOR_ALL_ACL ：此ACL授予创建者身份验证ID的所有权限
         * CreateMode ：创建节点的类型(4种类型)
         *              PERSISTENT：持久节点
         *              PERSISTENT_SEQUENTIAL：持久顺序节点
         *              EPHEMERAL：临时节点
         *              EPHEMERAL_SEQUENTIAL：临时顺序节点
         String node = zookeeper.create(path,data,acl,CreateMode);
         */

        // 持久节点
        String note_persisent = zooKeeper.create("/zk-persisent", "持久节点内容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        // 临时节点
        String note_ephemeral = zooKeeper.create("/zk-ephemeral", "临时节点内容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        // 持久顺序节点
        String note_persistent_sequential = zooKeeper.create("/zk-persistent-sequential", "持久顺序节点内容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

        System.out.println("持久节点：" + note_persisent);
        System.out.println("临时节点：" + note_ephemeral);
        System.out.println("持久顺序节点：" + note_persistent_sequential);
    }
}
